<?php
namespace Admin\Model;
use Think\Model;
/**
 * create table art_ip(
    -> id INT(8) NOT NULL PRIMARY KEY AUTO_INCREMENT,
    -> name VARCHAR(45) NOT NULL UNIQUE,
    -> title VARCHAR(45) default "",
    -> isopen INT(8) NOT NULL default 0);
*/
class IpModel extends Model{
	private $_id;
	private $_name;
	private $_title;
	private $_isopen;	// 是否开启使用，如果没有开启该项，所有来自该IP地址的管理员账号都将不可使用
	const IP_OPEN = 1;
	const IP_CLOSE = 0;

	public function addIp($name, $title = "", $isopen = self::IP_OPEN){
		if(empty($name))return false;
		$this->_name = $name;
		$this->_title = $title;
		$this->_isopen = $isopen;
		try{
			$this->parseIp();
			$this->parseOpen();
		}catch(\Exception $e){
			throw $e;
		}
		return $this->add($this->combine(true));
	}

	public function getOpens(){
		$map['isopen'] = self::IP_OPEN;
		return $this->where($map)->select();
	}

	public function setOpen($id, $isopen){
		$data['isopen'] = $isopen;
		return $this->where(array('id'=>$id))->save($data);
	}

	private function combine($needid = true){
		$res = array();
		if($needid == true){
			$res['id'] = $this->_id;
		}
		$res['name'] = $this->_name;
		$res['title'] = $this->_title;
		$res['isopen'] = $this->_isopen;
		return $res;
	}

	private function parseIp(){	// 解析IP地址是否正确
		$ips = explode('.', $this->_name);
		if(count($ips)!=4){
			throw new \Exception('请输入以点分法确定的十进制IP地址字符串');
		}else{
			foreach($ips as $v){
				if($v>255 || $v<0){
					throw new \Exception('IP地址格式不正确，请确保每段的值在0-255之间');
				}
			}
			// IP address is ok
		}
	}

	private function parseOpen(){
		switch($this->_isopen){
			case self::IP_OPEN:
				break;
			case self::IP_CLOSE:
				break;
			default:
				$this->_isopen = self::IP_OPEN;
				break;
		}
	}
}
